from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import json
from flask import render_template
from flask import request
from flask import session
from sqlalchemy.testing import in_

from info import db
from info.models import News, User, Comment, CommentLike
from info.modules import news
from info.utlis.captcha.response_code import RET
from info.utlis.commond import user_login_data
from . import news_blu


@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    if not g.user:
        return jsonify(erron=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR, errmsg="查询数据库失败")

    if not target_user:
        return jsonify(erron=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            return jsonify(erron=RET.DATAEXIST, errmsg="当前已关注")
        target_user.followers.append(g.user)
    else:
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            target_user.followers.remove(g.user)

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.DBERR, errmsg="数据保存错误")

    return jsonify(erron=RET.OK, errmsg="操作成功")


@news_blu.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
       return jsonify(erron=RET.SESSIONERR, errmsg="用户未登录")
    # 获取参数
    data_dict = request.json
    comment_id = data_dict.get("comment_id")
    news_id = data_dict.get("news_id")
    action = data_dict.get("action")
    # 校验参数
    if not all([comment_id, news_id, action]):
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
        comment_id = int(comment_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")
    if action not in ["add", "remove"]:
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")

    # 查找评论数据
    try:
        comment = Comment.query.get(comment_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.DBERR, errmsg="数据查询失败")
    if not comment:
        return jsonify(erron=RET.NODATA, errmsg="评论不存在")

    if action == "add":
        comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id, CommentLike.user_id == g.user.id).first()
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.comment_id = comment_id
            comment_like_model.user_id = g.user.id
            db.session.add(comment_like_model)
            comment.like_count += 1
    else:
        # 删除点赞数据
        comment_like_model = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(erron=RET.DBERR, errmsg="操作失败")

    return jsonify(erron=RET.OK, errmsg="点赞操作成功")


@news_blu.route("/news_comment", methods = ["POST"])
@user_login_data
def comment_news():
    user = g.user
    if not user:
        return jsonify(erron=RET.SESSIONERR, errmsg="用户未登录")
    # 获取参数
    data_dict = request.json
    news_id = data_dict.get("news_id")
    comment_content = data_dict.get("comment")
    parent_id = data_dict.get("parent_id")
    # 校验参数
    if not all([news_id, comment_content]):
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")
    # 查询参数
    try:
        news = News.query.get(news_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.DBERR, errmsg="数据查询错误")

    if not news:
        return jsonify(erron=RET.DBERR, errmsg="新闻不存在")
    # 评论对象
    comment = Comment()
    comment.news_id = news_id
    comment.content = comment_content
    comment.user_id = user.id
    if parent_id:
        comment.parent_id = parent_id
    # 保存到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as error:
        current_app.logger.error(error)
        db.session.rollback()
        return jsonify(erron=RET.DBERR, errmsg="保存数据错误")

    return jsonify(erron=RET.OK, errmsg="操作成功", data=comment.to_dict())


@news_blu.route("/news_collect", methods=["POST"])
@user_login_data
def collected_is_or_not():
    """收藏和取消收藏功能"""
    # 1.判断用户是否登录
    user = g.user
    if not user:
        return jsonify(erron=RET.SESSIONERR,errmsg="用户未登录")
    # 2.获取数据
    request_data = request.json
    news_id = request_data.get("news_id")
    action = request_data.get("action")
    # 3.校验参数
    if not all([news_id, action]):
        return jsonify(erron=RET.PARAMERR,errmsg = "参数错误")
    try:
        news_id = int(news_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")
    if action not in ["collect", "cancel_collect"]:
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")
    # 4.查询新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.DBERR, errmsg="数据查询错误")
    if not news:
        return jsonify(erron=RET.NODATA, errmsg="未查询到数据")
    # 收藏
    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)
    # 取消收藏
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    return jsonify(erron=RET.OK, errmsg="操作成功")


@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    user = g.user
    # 2 增加右侧新闻的排行显示
    # 2.1取出右侧新闻
    news_list = list()
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)  # 查询结果对象的列表
    except Exception as error:
        current_app.logger.error(error)
    # 2.2将每一个列表对象的属性转换成可写入模板的字典格式
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 3.新闻查询，并返回给前端
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as error:
        current_app.logger.error(error)

    if not news:
        abort("404")

    news.clicks += 1
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True
    # 查询评论数据
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as error:
        current_app.logger.error(error)

    comment_like_ids = []
    if g.user:
        # 取出所有当前页面所有评论的id
        comment_ids = [ comment.id for comment in comments]
        # 筛选出所有评论里面被当前用户点过赞的
        comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_ (comment_ids), CommentLike.user_id == g.user.id)
        # 取出被当前用户点赞的评论id
        comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]

    comment_dict_li = []
    for comment in comments:
        comment_dict = comment.to_dict()
        # 初始都没有点赞
        comment_dict["is_like"] = False
        # 在列表中的表示被点赞，显示样式
        if comment.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_dict_li.append(comment_dict)

    # 完善关注与被关注功能

    # 当前登录用户是否关注当前新闻作者
    is_followed = False
    # if 当前新闻有作者，并且 当前登录用户已关注过这个用户
    if news.user and user:
        # if user 是否关注过 news.user
        if news.user in user.followed:
            is_followed = True

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "is_followed": is_followed,
        "comments": comment_dict_li
    }

    return render_template("news/detail.html", data=data)

    # 1.3.用户登录后信息传入模板进行渲染
    # data = {
    #     "user": user.to_dict() if user else None,
    #     "news_dict_li": news_dict_li,
    #     "news": news.to_dict(),
    #     "is_collected": is_collected,
    #     "comments": comment_dict_li
    # }
    # return render_template("news/detail.html", data=data)